﻿using System;
using System.Net;
using System.Threading.Tasks;
using System.IO;

namespace Services.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class HttpResponseMessageWrapper : IHttpResponseMessage
    {
        private readonly HttpWebResponse _httpWebResponseMessage;

        public HttpResponseMessageWrapper(HttpWebResponse httpResponseMessage)
        {
            _httpWebResponseMessage = httpResponseMessage;
        }

        public Task<string> ReadAsStringAsync()
        {
            return Task.Run(() => ReadAsString());
        }

        private string ReadAsString()
        {
            if (_httpWebResponseMessage == null)
                return string.Empty;
            string header = _httpWebResponseMessage.Headers["Content-Encoding"];
            Stream stream;
            stream = _httpWebResponseMessage.GetResponseStream();

            using (var resder = new StreamReader(stream))
            {
                return resder.ReadToEnd();
            }

        }

        public Task<byte[]> ReadAsByteArrayAsync()
        {
            return null;
        }

        public Task<Stream> ReadAsStreamAsync()
        {
            return null;
        }

        public string[] GetCookies()
        {
            if (_httpWebResponseMessage == null)
                return null;
            string cookCollect = _httpWebResponseMessage.Headers["Set-Cookie"];

            if (string.IsNullOrEmpty(cookCollect))
                return null;

            string[] parts = cookCollect.Split(new string[] { ",  " }, StringSplitOptions.RemoveEmptyEntries);

            return parts;
        }
    }
}
